package com.wrupple.muba.desktop.client.bootstrap.state.impl;

import java.util.Collection;
import java.util.Map;

import com.google.gwt.activity.shared.Activity;
import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;
import com.wrupple.muba.common.shared.StateTransition;
import com.wrupple.muba.desktop.client.bootstrap.state.RegisterModuleActivities;
import com.wrupple.muba.desktop.client.module.DesktopActivityMapper;
import com.wrupple.muba.desktop.client.module.ForkedActivity;
import com.wrupple.muba.desktop.client.module.ForkedActivity.InjectedActivity;
import com.wrupple.muba.desktop.domain.DesktopLoadingStateHolder;

public class RegisterModuleActivitiesImpl implements RegisterModuleActivities {

	DesktopActivityMapper activityMapper;
	@Inject
	public RegisterModuleActivitiesImpl(DesktopActivityMapper activityMapper) {
		super();
		this.activityMapper = activityMapper;
	}


	@Override
	public void start(DesktopLoadingStateHolder parameter,
			StateTransition<DesktopLoadingStateHolder> onDone, EventBus bus) {
	Map<String, Activity> activityMap = parameter.getActivityMap();
		
		activityMapper.setDesktopActivityMap(activityMap );
		
		Collection<Activity> allactivities = activityMap.values();
		Activity parent;
		ForkedActivity parentForkedActivity;
		ForkedActivity.InjectedActivity option;
		String parentActivity;
		String distinctiveValue;

		for (Activity act : allactivities) {
			if (act instanceof ForkedActivity.InjectedActivity) {
				option = (InjectedActivity) act;
				parentActivity = option.getForkedActivityId();
				distinctiveValue = option.getOptionDistinctiveValue();
				parent = activityMap.get(parentActivity);
				if (parent != null && parent instanceof ForkedActivity) {
					parentForkedActivity = (ForkedActivity) parent;
					parentForkedActivity.registerActivity(distinctiveValue, option);
				}
			}
		}
		
		onDone.setResultAndFinish(parameter);		
	}

}
